﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using LeadThing.AbpZeroTemplate.Common.Secutiry;
using Newtonsoft.Json;

namespace LeadThing.AbpZeroTemplateShortMessage
{
    public class MasShortMessage
    {
        #region MDK提供方Demo

        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="_mobiles">手机号</param>
        /// <param name="_content">短信内容</param>
        /// <returns></returns>
        public bool SendMessage(string _mobiles, string _content)
        {
            //Http地址
            string ContentType = "application/x-www-form-urlencoded";//类型application/x-www-form-urlencoded
            string Url = "http://112.35.1.155:1992/sms/norsubmit";//正式http地址
            MasShortMessageModel model = new MasShortMessageModel()
            {
                ecName = "中国共产党莒县委员会政法委员会",
                apId = "jxmsg",
                secretKey = "123456",
                mobiles = _mobiles,
                content = _content,
                sign = "Aqxk7pOWl",
                addSerial = ""
            };

            Md5Helper md5Helper = new Md5Helper();
            model.mac = GetMd5Hash(model.ecName + model.apId + model.secretKey + model.mobiles + model.content + model.sign + model.addSerial);
            string body = Base64Helper.Base64Encode(JsonConvert.SerializeObject(model));
            string responseContent = HttpPost(Url, body, ContentType);
            ResultModel resultModel = (ResultModel)JsonConvert.DeserializeObject(responseContent, typeof(ResultModel));
            return resultModel.success;
        }

        //登录验证
        public static string PostHttp_Login(string url, string LoginType, string Ecname, string Username, string Password, string contentType)
        {
            url += LoginType;
            string responseContent = "准备登录";
            string body = "ec_name=" + Ecname + "&user_name=" + Username + "&user_passwd=" + Password;

            responseContent = HttpPost(url, body, contentType);
            return responseContent;
        }

        //短信发送
        private static string Http_SendSms(string url, string senttype, string mas_user_id, string mobiles, string content, string sign, string seria, string mac, string contentType)
        {
            url += senttype;
            string body = "mas_user_id=" + mas_user_id + "&mobiles=" + mobiles + "&content=" + content + "&sign=" + sign + "&serial=" + seria + "&mac=" + mac;
            Console.WriteLine("【连接】：" + url + body);
            string SentStatus = "准备发送";

            SentStatus = HttpPost(url, body, contentType);
            //SentStatus = WebPost(url, body, contentType);
            return SentStatus;
        }

        private static string Http_SendTSms(string url, string senttype, string mas_user_id, string tempId, string param, string mobiles, string content, string sign, string seria, string mac, string contentType)
        {
            url += senttype;
            string body = "mas_user_id=" + mas_user_id + "&template_id=" + tempId + "&params=" + param + "&mobiles=" + mobiles + "&content=" + content + "&sign=" + sign + "&serial=" + seria + "&mac=" + mac;
            Console.WriteLine("【连接】：" + url + body);
            string SentStatus = "准备发送";

            SentStatus = HttpPost(url, body, contentType);
            //SentStatus = WebPost(url, body, contentType);
            return SentStatus;
        }


        //MD5计算mac
        public static string GetMd5Hash(String input)
        {
            if (input == null)
            {
                return null;
            }

            MD5 md5Hash = MD5.Create();

            // 将输入字符串转换为字节数组并计算哈希数据  
            byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));

            // 创建一个 Stringbuilder 来收集字节并创建字符串  
            StringBuilder sBuilder = new StringBuilder();

            // 循环遍历哈希数据的每一个字节并格式化为十六进制字符串  
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            // 返回十六进制字符串  
            return sBuilder.ToString();
        }

        //HttpPost方法
        //body是要传递的参数,格式"roleId=1&uid=2"
        //post的cotentType填写:
        //"application/x-www-form-urlencoded"
        //soap填写:"text/xml; charset=utf-8"
        //http登录post
        private static string HttpPost(string Url, string Body, string ContentType)
        {
            string ResponseContent = "";
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(Url);

            httpWebRequest.ContentType = ContentType;
            httpWebRequest.Method = "POST";
            httpWebRequest.Timeout = 20000; //setInstanceFollowRedirects
            httpWebRequest.MediaType = "json";

            byte[] btBodys = Encoding.UTF8.GetBytes(Body);
            httpWebRequest.ContentLength = btBodys.Length;
            httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);

            try
            {


                HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
                ResponseContent = streamReader.ReadToEnd();

                httpWebResponse.Close();
                streamReader.Close();
                httpWebRequest.Abort();
                httpWebResponse.Close();
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
            return ResponseContent;
        }

        //HttpPost方法
        //body是要传递的参数,格式"roleId=1&uid=2"
        //post的cotentType填写:
        //"application/x-www-form-urlencoded"
        //soap填写:"text/xml; charset=utf-8"
        //http登录post
        private static string WebPost(string Url, string Body, string ContentType)
        {
            string ResponseContent = "";
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(Url);

            httpWebRequest.ContentType = ContentType;
            httpWebRequest.Method = "POST";
            httpWebRequest.Timeout = 20000;

            byte[] btBodys = Encoding.UTF8.GetBytes(Body);
            httpWebRequest.ContentLength = btBodys.Length;
            httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);


            StreamReader stream = null;
            try
            {
                using (WebResponse response = httpWebRequest.GetResponse())
                {
                    stream = new StreamReader(response.GetResponseStream());
                }
            }
            catch (WebException e)
            {
                stream = new StreamReader(e.Response.GetResponseStream());
            }

            ResponseContent = stream.ReadToEnd();
            return ResponseContent;
        }

        #endregion
    }
}
